<template>
  <MainSlot v-loading="loading">
    <template v-slot:searchForm>
      <SearchForm :formItemList="formItemList" @search="search"></SearchForm>
    </template>

    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>

    <template v-slot:table>
      <TableData :config="table_config" :tableThead="tableThead" :dataList="dataList" :loading="loading"
        @selection-change="selectionChange">
        <template v-slot:facilityVOList="{ row }">
          <el-button type="text" @click="lookView(row)">查看设施</el-button>
        </template>

        <template v-slot:inspectionPointCode="{ row }">
          <el-button type="text" @click="qrShow(row.inspectionPointCode)">查看二维码</el-button>
        </template>
      </TableData>
    </template>

    <template v-slot:pagination>
      <Pagination @size-Change="handleSizeChange" :size="size" @current-change="handleCurrentChange" :page="page">
      </Pagination>
    </template>

    <template v-slot:dialogModule>
      <AddEdit :title="'巡查点'" @closeDialog="closeDialog" :addEditFlag="addEditFlag" :dialogVisible="dialogVisible"
        :facilityList="facilityList" :data="formData">
      </AddEdit>
      <el-dialog :close-on-click-modal="false" title="设施详情" :visible.sync="dialogVisible_lookView" width="60%"
        :before-close="handleClose">
        <el-table :data="facilityVOList" style="width: 100%" border>
          <el-table-column type="index" label="序号" width="55" align="center" />
          <el-table-column prop="facilityName" label="设施名称">
          </el-table-column>
          <el-table-column prop="facilityNo" label="设施编号">
          </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible_lookView = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisible_lookView = false">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog :close-on-click-modal="false" title="查看二维码" :visible.sync="qrCodeShow" width="20%" center>
        <div class="qrCode">
          <vue-qr :text="qrText" :margin="0" color-dark="#000" color-light="#fff" :logo-scale="0.15" :dot-scale="1"
            :size="200" />
        </div>
      </el-dialog>
    </template>
  </MainSlot>
</template>

<script>
import MainSlot from "@/components/MainSlot";
import Pagination from '@/components/Pagination';
import SearchForm from '@/components/SearchForm';
import TableData from '@/components/TableData';
import BtnSlot from '@/components/BtnSlot';
import vueQr from "vue-qr";
import AddEdit from './components/addEdit.vue';
import patrolInfoManage from "@/api/patrol-info-manage/patrol-point-manage";
import facilityManagement from '@/api/digtalOperation/facilityManagement';

export default {
  components: { MainSlot, Pagination, SearchForm, TableData, BtnSlot, AddEdit, vueQr },
  data() {
    return {
      loading: false,
      qrCodeShow: false,
      dialogVisible: false,
      dialogVisible_lookView: false,
      addEditFlag: 'add',
      formData: {},
      page: 1,
      size: 10,
      qrText: '',
      selectIndex: 0,
      btnList: ['add', 'delete'],
      dataList: [],
      facilityVOList: [],
      tableThead: [
        { isShow: true, label: '巡查点名称', prop: 'inspectionPointName' },
        { isShow: true, label: '允许误差范围（米）', prop: 'errorRange' },
        { isShow: true, label: '关联鱼塘名称', slotName: 'facilityVOList' },
        { isShow: true, label: '查看二维码', slotName: 'inspectionPointCode' },

      ],
      // 配置项
      table_config: {
        isCheckBox: true,

        isOperation: true,
        // 表格操作列
        operation: {
          label: '操作',
          width: '200',
          cols: [
            {
              label: '编辑',
              type: 'primary',
              flag: 'edit',
              handleRow: this.handleRow
            },
            {
              label: '删除',
              type: 'danger',
              flag: 'delete',
              handleRow: this.handleRow
            }
          ]
        },
      },
      formItemList: [
        {
          label: '巡查点名称',
          type: 'input',
          param: 'inspectionPointName',
          multiple: false,
          isShow: true
        }
      ],
      facilityList: []
    }
  },
  mounted() {
    this.queryPageByCondition();
    this.initData();
  },

  methods: {
    async initData() {
      //获取养殖设施；
      let { data: facilityList } = await facilityManagement.getFacilityListByConditionAll({
        breedType: sessionStorage.breedType
      });
      this.facilityList = facilityList || [];
    },
    delList(deleteList = [], key = 'inspectionPointId') {
      let list = []
      deleteList.forEach(item => {
        list.push(item[key])
      })
      console.log(list)
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        patrolInfoManage.delInspectionPointInfo(list).then(res => {
          if (res.code == 1) {
            this.$message.success(res.msg || '删除成功');
            this.queryPageByCondition();
          } else {
            this.$message.warning(res.msg || '删除失败');
          }
        }).catch(err => {
          console.log(err)
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    queryPageByCondition() {
      let params = {
        page: this.page,
        size: this.size,
        entity: {
          ...this.searchFormData
        }
      }
      patrolInfoManage.getInspectionPointList(params).then(res => {
        this.dataList = [];
        if (res.code == 1) {
          this.dataList = res.data.content || [];
          this.total = res.data.totalElements;
          if (res.data.totalPages && this.page > res.data.totalPages) {
            this.page = res.data.totalPages;
            this.queryPageByCondition();
          }
        } else {
          this.$message.warning(res.msg || '分页查询失败')
        }
      }).catch(err => {
        console.log(err)
      })
    },
    search(data) {
      this.page = 1;
      this.searchFormData = { ...this.searchFormData, ...data };
      this.queryPageByCondition();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.queryPageByCondition();
    },
    handleSizeChange(size) {
      this.size = size;
      this.queryPageByCondition();
    },
    qrShow(inspectionPointCode) {
      let facilityNo = inspectionPointCode;
      if (!facilityNo) {
        this.$message.warning("请先选择巡查点！！！");
        return;
      }
      let newqrdata = {
        url: `https://matefarm.net/mateFarmTraceSource/#/pages/facility-messages/facility-message?facilityNo=${facilityNo}`
      };
      this.qrText = newqrdata.url;
      console.log(this.qrText)
      setTimeout(() => {
        this.qrCodeShow = true;
      }, 200);
    },
    lookView(row) {
      this.facilityVOList = row.facilityVOList || [];
      if (this.facilityVOList.length == 0) {
        this.$message.warning('暂无设施详情')
      } else {
        this.dialogVisible_lookView = true;
      }
    },
    // 操作方法
    handleRow(rowData, item) {
      if (item.flag == 'edit') {
        this.dialogVisible = true;
        this.formData = JSON.parse(JSON.stringify(rowData))
      } else if (item.flag == 'delete') {
        this.delList([rowData]);
      }
      this.addEditFlag = item.flag
    },
    // 多选方法
    selectionChange(val) {
      this.selectList = val || []
    },
    //获取选中Btn
    getBtnEvent(flag) {
      console.log(flag)
      if (flag == 'add') {
        this.dialogVisible = true
      } else if (flag == 'delete') {
        if (this.selectList.length > 0) {
          this.delList(this.selectList)
        } else {
          this.$message.warning('请先选择表单数据项后再删除！')
        }
      }
      this.addEditFlag = flag
    },
    //关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
      this.queryPageByCondition();
    },

    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    }
  }
};
</script>

<style lang="scss" scoped>
.pointer {
  cursor: pointer;
}

.qrCode {
  display: flex;
  justify-content: center;
}
</style>